package com.example.fsd.service.configs;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.fsd.common.result.R;
import com.example.fsd.pojo.Configs;
import com.example.fsd.mapper.ConfigsMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangguihong
 * @since 2024-11-20
 */
@Service
public class ConfigsServiceImpl extends ServiceImpl<ConfigsMapper, Configs> implements IConfigsService {

    @Override
    public R findOneConfigs() {
        LambdaQueryWrapper<Configs> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.last("limit 1");
        return R.ok().put("list",this.list(lambdaQueryWrapper));
    }

    @Override
    public R updateConfigsLogo(MultipartFile logo) {
        System.out.println("updateConfigsLogo:" + logo);

        // 确保文件不为空
        if (logo == null || logo.isEmpty()) {
            return R.error("上传的文件不能为空");
        }
        // 获取文件名和扩展名
        String originalFilename = logo.getOriginalFilename();
        if (originalFilename == null) {
            return R.error("无法获取文件名");
        }
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 创建新的文件名
        String newFilename = System.currentTimeMillis() + fileExtension;
        // 拼接绝对路径，确保使用完整路径
        String basePath = "/www/wwwroot/fsdadminapi.kfcit.com/upload"; // 修改为合适的绝对路径
        String filePath = basePath + "/" + newFilename;
        System.out.println(filePath);
        // 创建目录
        File directory = new File(basePath);
        if (!directory.exists()) {
            boolean dirCreated = directory.mkdirs(); // 创建多级目录
            if (dirCreated) {
                System.out.println("Directory created: " + directory.getAbsolutePath());
            } else {
                return R.error("无法创建目录，请检查权限");
            }
        }
        try {
            // 保存文件
            logo.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace(); // 打印异常堆栈
            return R.error("文件保存失败: " + e.getMessage());
        }

        // 更新数据库中的文件路径
        Configs configs = this.getOne(new LambdaQueryWrapper<Configs>().eq(Configs::getId, 1));
        configs.setLogo("/upload/" + newFilename); // 这里设置为相对路径
        this.updateById(configs);
        // 返回完整的 URL
        String fileUrl = "/upload/" + newFilename; // 根据实际情况修改服务器地址和端口
        return R.ok().put("url", fileUrl);
    }
    @Override
    public R updateConfigsText(Configs configs) {
        //setid
        configs.setId(1);
        System.out.println("updateConfigsText:" + configs);
        boolean b = updateById(configs);
        if (!b) {
            throw new RuntimeException("更新失败");
        }
        return R.ok();
    }
}
